package com.zenithmind.gateway.config;

import com.zenithmind.gateway.route.RouteConfigurer;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Comparator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder.Builder;

/**
 * 网关路由配置类
 * 使用模块化的路由配置器来管理所有微服务的API路由配置
 * 遵循开闭原则：新增路由配置器无需修改此类
 * 遵循单一职责原则：只负责协调各个路由配置器
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class ModularRouteConfiguration {

    private final Environment env;
    private final GatewayRouteProperties gatewayRouteProperties;
    private final DefaultRouteConfigProvider defaultRouteConfigProvider;
    private final List<RouteConfigurer> routeConfigurers;

    /**
     * 创建路由定位器
     * 使用模块化的路由配置器来构建路由
     */
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        log.info("初始化网关路由配置...");
        
        Builder routes = builder.routes();
        
        // 按优先级排序路由配置器
        routeConfigurers.stream()
            .sorted(Comparator.comparingInt(RouteConfigurer::getOrder))
            .forEach(configurer -> {
                log.info("应用路由配置器: {}", configurer.getConfigureName());
                configurer.configureRoutes(routes);
            });
        
        log.info("网关路由配置完成，共应用了 {} 个路由配置器", routeConfigurers.size());
        return routes.build();
    }
}
